#include <string>
#include <iostream>
#include "BackupFS.h"
#include "logger/BackupFSLogger.h"
#include "../cmdlinefile/cmdtest.h"
#include <thread>
std::shared_ptr<BackupFS::BackupVFS> _BackupFS;

void MountFS(const std::wstring& data_path, const std::wstring& mount_point, LONGLONG fs_size)
{
	if (!_BackupFS)
	{
		_BackupFS = std::make_shared<BackupFS::BackupVFS>();
	}

	if (!_BackupFS->Mount(data_path, mount_point, fs_size))
	{
		return;
	}
	_BackupFS->Wait();
}
BACKUPFS_CMD(mount, <data path> <mount point> [filesystem size] create or mount a BackupFS file system)
{
	if (args.size() < 2)
	{
		BackupFS::Logger->Error("Please input the data path,mount point");
		return false;
	}
	LONGLONG fs_size = 0;
	if (args.size() > 2)
	{
		fs_size = BackupFS::ParseSizeWithUnit(args[2]);
		if (fs_size == 0)
		{
			fs_size = atoll(args[2].c_str());
		}
	}
	std::thread t(&MountFS, BackupFS::S2W(args[0]), BackupFS::S2W(args[1]),fs_size);
	t.detach();

	return true;
}
BACKUPFS_CMD(umount, Unmount the Current BackupFS file system)
{
	if (_BackupFS)
	{
		_BackupFS->Umount();
		_BackupFS.reset();
	}
	BackupFS::Logger->Info("Unmount the BackupFS file system");
	return true;
}
BACKUPFS_CMD(setflushfrequency, <frequency> set the filesystem flush frequency(seconds))
{
	if (args.size() < 1)
	{
		BackupFS::Logger->Error("Please input the frequency");
		return false;
	}
	if (_BackupFS)
	{
		_BackupFS->SetFlushFrequency(atoi(args[0].c_str()));
		BackupFS::Logger->Info("Set the file system flush frequency to ", args[0]);
	}
	return true;
}
BACKUPFS_CMD(setreadonly, <0/1> set readonly FS)
{
	int readonly = 0;
	if (args.size() > 0)
	{
		readonly = atoi(args[0].c_str());
	}
	if (_BackupFS)
	{
		_BackupFS->SetReadOnly(readonly);
	}
	BackupFS::Logger->Info("Set readonly done.");
	return true;
}
BACKUPFS_CMD(setsize, <size> set FS size)
{
	LONGLONG size = 0;
	if (args.size() == 0)
	{
		BackupFS::Logger->Error("Please input the file system size");
		return false;
	}
	if (_BackupFS)
	{
		size = BackupFS::ParseSizeWithUnit(args[0]);
		if (size == 0)
		{
			size = atoll(args[0].c_str());
		}
		_BackupFS->SetFsSize(size);
	}
	BackupFS::Logger->Info("Set file system size done.");
	return true;
}
int wmain(int argc, wchar_t* argv[])
{
	if (std::filesystem::exists(L"log.txt"))
	{
		std::filesystem::remove(L"log.txt");
	}
	BackupFS::BackupFSLogger::GetInstance()->SetLogFile(L"log.txt");
	BackupFS::BackupFSLogger::GetInstance()->Info("Log file name is log.txt");
	BackupFS::BackupFSLogger::GetInstance()->SetLogLevel(BackupFS::LevelInfo | BackupFS::LevelError|BackupFS::LevelWarning/* | BackupFS::LevelDebug*/);
	BackupFSShell cmd;
	return cmd.RunCmdLines("BackupFS", argc, argv) ? 0 : 1;
}